
package com.lowang.test.springmvc.handler;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * 通用错误处理器.
 *
 * @author Wang.ch
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
@Controller
@RequestMapping("/error")
public class ControllerExceptionHandler implements HandlerExceptionResolver {
  private static final Logger LOGGER = LoggerFactory.getLogger(ControllerExceptionHandler.class);

  protected ModelAndView handleViewError(
      String url, String errorStack, String errorMessage, String viewName) {
    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", errorStack);
    mav.addObject("url", url);
    mav.addObject("msg", errorMessage);
    mav.addObject("timestamp", new Date());
    mav.setViewName(viewName);
    return mav;
  }

  protected ModelAndView handleJSONError(
      HttpServletResponse rsp, String errorMessage, HttpStatus status) throws IOException {
    rsp.setCharacterEncoding("UTF-8");
    rsp.setContentType(MediaType.TEXT_PLAIN.toString());
    rsp.setStatus(status.value());
    PrintWriter writer = rsp.getWriter();
    writer.write(errorMessage);
    writer.flush();
    writer.close();
    return null;
  }

  @Override
  public ModelAndView resolveException(
      HttpServletRequest req, HttpServletResponse res, Object obj, Exception ex) {
    try {
      LOGGER.error("全局异常:", ex);
      return handleJSONError(res, ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (IOException e) {
    }
    return null;
  }
}
